package com.sdy.dcsb.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.model.EsbConsumerSystemIp;
import com.sdy.dcsb.biz.model.EsbServiceConsumer;
import com.sdy.dcsb.biz.model.EsbSystemService;
import com.sdy.dcsb.biz.service.EsbConsumerSystemIpService;
import com.sdy.dcsb.biz.service.EsbServiceConsumerService;
import com.sdy.dcsb.biz.service.EsbSystemServiceService;
import com.sdy.dcsb.biz.service.UserOperationLogService;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 * 服务消费者系统下群组的IP信息表 前端控制器
 * </p>
 *
 * @author fb
 * @since 2019-09-29
 */
@Slf4j
@Controller
@RequestMapping("/EsbConsumerSystemIp")
@Api(tags = "消费者系统群组的ip信息相关接口")
public class EsbConsumerSystemIpController extends BaseController {
    @Autowired
    private EsbConsumerSystemIpService esbConsumerSystemIpService;
    @Autowired
    private EsbSystemServiceService esbSystemServiceService;
    @Autowired
    private EsbServiceConsumerService esbServiceConsumerService;
    @Autowired
    private UserOperationLogService userOperationLogService;

    /**
     * 群组下ip信息，分页数据，可按ip地址模糊查询
     * @param groupid 当前群组id
     * @param message ,按IP地址模糊查询，查询值
     * @param page [current, size]
     * @return
     */
    @GetMapping("/pageData")
    @ResponseBody
    @ApiOperation("群组下ip信息，分页数据，可按ip地址模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "groupid", value = "当前群组id"),
            @ApiImplicitParam(dataType = "String", name = "message", value = "按IP地址模糊查询，查询值"),
            @ApiImplicitParam(dataType = "String", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "String", name = "size", value = "每页数量"),
    })
    public Response pageData(Integer groupid, String message, Page<EsbConsumerSystemIp> page) {
        if(isEmpty(groupid)) {
            return Response.error("请求群组id不能为空");
        }
        LambdaQueryWrapper<EsbConsumerSystemIp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EsbConsumerSystemIp::getGroupid,groupid);
        wrapper.orderByDesc(EsbConsumerSystemIp::getId);
        if(!isEmpty(message)) {
            try {
                message = URLDecoder.decode(message,"utf-8");
            }catch(IOException e) {

            }
            wrapper.like(EsbConsumerSystemIp::getIp,message);
        }
        IPage<EsbConsumerSystemIp> result = esbConsumerSystemIpService.page(page, wrapper);
        return Response.success(result);
    }

    /**
     * 查询单条ip信息
     * @param id ,当前ip表id
     * @return
     */
    @GetMapping("/select")
    @ResponseBody
    @ApiOperation("查询单条ip信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前ip表id"),
    })
    public Response select(Integer id) {
        if(!isEmpty(id)){
            return Response.success(esbConsumerSystemIpService.getById(id));
        }else {
            return Response.error("id不能为空");
        }
    }

    /**
     * 修改当前群组下的ip信息
     * @param id ,当前ip表id
     * @param ip ,ip地址
     * @param port ,端口
     * @return
     */
    @GetMapping("/update")
    @ResponseBody
    @ApiOperation("修改当前群组下的ip信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前ip表id"),
            @ApiImplicitParam(dataType = "String", name = "ip", value = "ip地址"),
            @ApiImplicitParam(dataType = "String", name = "port", value = "端口"),
    })
    public Response updateName(HttpServletRequest request, Integer id, String ip, String port) {
        if(!isEmpty(ip) || !isEmpty(port)) {
            try {
                ip = URLDecoder.decode(ip,"utf-8");
                port = URLDecoder.decode(port,"utf-8");
            }catch(IOException e) {

            }
            EsbConsumerSystemIp esbConsumerSystemIp = new EsbConsumerSystemIp();
            esbConsumerSystemIp.setIp(ip);
            esbConsumerSystemIp.setPort(port);
            esbConsumerSystemIp.setStatus("1");
            userOperationLogService.savaUserLog(request, "修改消费者ip信息：" + esbConsumerSystemIpService.getById(id).getIp());
            return Response.success(esbConsumerSystemIpService.update(esbConsumerSystemIp, new UpdateWrapper<EsbConsumerSystemIp>().eq("id", id)));
        }else {
            return Response.error("ip或端口不能为空");
        }
    }

    /**
     * 在当前群组下新增ip信息
     * @param systemid ,当前系统id
     * @param groupid ,当前群组id
     * @param ip ,ip地址
     * @param port ,端口
     * @return
     */
    @GetMapping("/insert")
    @ResponseBody
    @ApiOperation("在当前群组下新增ip信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "systemid", value = "当前系统id"),
            @ApiImplicitParam(dataType = "Integer", name = "groupid", value = "当前群组id"),
            @ApiImplicitParam(dataType = "String", name = "ip", value = "ip地址"),
            @ApiImplicitParam(dataType = "String", name = "port", value = "端口"),
    })
    public Response insert(HttpServletRequest request, Integer systemid, Integer groupid, String ip, String port) {
        if(!isEmpty(ip) || !isEmpty(port) || !isEmpty(systemid) || !isEmpty(port)) {
            try {
                ip = URLDecoder.decode(ip, "utf-8");
                port = URLDecoder.decode(port, "utf-8");
            } catch (IOException e) {

            }
            LambdaQueryWrapper<EsbConsumerSystemIp> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EsbConsumerSystemIp::getIp,ip);
            List<EsbConsumerSystemIp> esbConsumerSystemIpResult = esbConsumerSystemIpService.list(wrapper);
            if(esbConsumerSystemIpResult.size() != 0 ) {
                return Response.error("新增的ip已存在！");
            }
            EsbConsumerSystemIp esbConsumerSystemIp = new EsbConsumerSystemIp();
            esbConsumerSystemIp.setSystemid(systemid);
            esbConsumerSystemIp.setGroupid(groupid);
            esbConsumerSystemIp.setIp(ip);
            esbConsumerSystemIp.setPort(port);
            esbConsumerSystemIp.setStatus("1");
            if(esbConsumerSystemIpService.save(esbConsumerSystemIp)) {
                userOperationLogService.savaUserLog(request, "新增消费者ip信息：" + ip);
                QueryWrapper<EsbSystemService> esbSystemServiceWrapper = new QueryWrapper<>();
                esbSystemServiceWrapper.eq("system_id",systemid);
                List<EsbSystemService> esbSystemServiceWrapperResult = esbSystemServiceService.list(esbSystemServiceWrapper);
                for(int i=0; i<esbSystemServiceWrapperResult.size(); i++) {
                    Integer ipid = esbConsumerSystemIp.getId();
                    EsbServiceConsumer esbServiceConsumer = new EsbServiceConsumer();
                    esbServiceConsumer.setServcode(esbSystemServiceWrapperResult.get(i).getServcode());
                    esbServiceConsumer.setIpid(ipid);
                    esbServiceConsumer.setStatus("0");
                    esbServiceConsumer.setCreateTime(new Date());
                    esbServiceConsumer.setUpdateTime(new Date());
                    if(esbServiceConsumerService.save(esbServiceConsumer)) {
                        userOperationLogService.savaUserLog(request, "新增使用服务的消费者信息：" +
                                esbSystemServiceWrapperResult.get(i).getServcode() + " , " + ip);
                    }else {
                        esbConsumerSystemIpService.removeById(esbConsumerSystemIp.getId());
                        return Response.error("群组新增ip失败！");
                    }
                }
                return Response.success("群组新增ip成功！");
            }else {
                return Response.error("群组新增ip失败！");
            }
        }else {
            return Response.error("请求参数不能为空！");
        }
    }

    /**
     * 删除当前群组下ip信息
     * @param id ,当前ip表id
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    @ApiOperation("删除当前群组下ip信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前ip表id"),
    })
    public Response delete(HttpServletRequest request, Integer id) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        userOperationLogService.savaUserLog(request, "删除消费者ip信息：" + esbConsumerSystemIpService.getById(id).getIp());
        return Response.success(esbConsumerSystemIpService.removeById(id));
    }

}
